package com.uuj.dome.serviceimp;

import com.querydsl.core.types.dsl.BooleanExpression;
import com.querydsl.jpa.impl.JPAQuery;
import com.uuj.dome.entity.GoodEntity;
import com.uuj.dome.entity.QGoodEntity;
import com.uuj.dome.jpa.GoodJPA;
import com.uuj.dome.service.QueryService;
import com.uuj.dome.util.Inquirer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * ClassName:QueryServiceImpl
 * PACKAGE_NAME:com.uuj.dome.serviceimp
 */
@Repository
public class QueryServiceImpl implements QueryService {

    @Autowired
    GoodJPA goodJPA;

    // 注入EntityManager
    @PersistenceContext
    private EntityManager manager;

    @Override
    public List<GoodEntity> findAll() {
        // queryDSL查询实体类
        QGoodEntity goodEntity = QGoodEntity.goodEntity;
        // 构建jpa查询对象
        JPAQuery<GoodEntity> query = new JPAQuery<>(manager);
        // 返回查询结果接口
        return query
                //查询字段
                .select(goodEntity)
                // 查询表
                .from(goodEntity)
                // 查询条件
                .where(goodEntity.type.id.eq(Long.valueOf("1")))
                // 查询结果
                .fetch();
    }

    @Override
    public List<GoodEntity> join() {
        List<GoodEntity> list = new ArrayList<>();
        // queryDSL查询实体类
        QGoodEntity goodEntity = QGoodEntity.goodEntity;
        // 查询条件
        BooleanExpression id = goodEntity.type.id.eq(Long.valueOf("1"));
        // 执行查询
        Iterator<GoodEntity> iterator = goodJPA.findAll(id).iterator();
        while (iterator.hasNext()) {
            list.add(iterator.next());
        }
        return list;
    }

    @Override
    public List<GoodEntity> joinCustom() {
        // queryDSL查询实体类
        QGoodEntity goodEntity = QGoodEntity.goodEntity;
        // 自定义查询对象
        Inquirer inquirer = new Inquirer();
        // 查询条件
        inquirer.putExpression(goodEntity.type.id.eq(Long.valueOf("1")));
        // 返回查询结果
        return inquirer.iteratorToList(goodJPA.findAll(inquirer.buidleQuery()));
    }


}
